#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File  : upload.py
@Author: different && 道阻且长,行则将至 行而不辍,未来可期
@Date  : 2021/08/03
@Desc  : 蓝图视图

"""
import logging
import os
import uuid

from flask import render_template, request, jsonify, g

import settings
from apps.models.charts import DataSourceTitle, DataSourceContent
from apps.models.user import User
from apps.view import upload_bp
from expand import login_required, db, auth_management
from expand.exp_read_excel import ReadExcel


# 文件格式检测
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in settings.ALLOWED_EXTENSIONS


@upload_bp.route('/upload', methods=['GET', 'POST'])
@login_required
@auth_management
def upload_file():
    if request.method == 'GET':
        users = User.query.with_entities(User.nickname, User.id).filter_by(is_superuser=0).all()
        users = [{'value': i[1], 'name': i[0]} for i in users]
        return render_template('upload.html', users=users)

    if not (title := request.form.get('title')):
        return jsonify(code=400, msg='Error'), 400

    file = request.files['file']
    if allowed_file(file.name):
        return jsonify(code=415, msg='Error'), 415
    # 文件名
    filename = uuid.uuid4().hex + os.path.splitext(file.filename)[-1]
    file.save(os.path.join(settings.UPLOAD_FOLDER, filename))
    # 写入数据库
    try:
        user_id = request.form.get('user_id')
        user = User.query.filter_by(id=user_id).first()
        query_title = DataSourceTitle(title=title, filename=filename, upload_user=g.user.nickname)
        query_title.users.append(user)
        db.session.add(query_title)
        db.session.flush()
        excel_data = ReadExcel(filename)
        content_list = excel_data.data_source()
        for ls in content_list:
            ls['table_id'] = query_title.id
            content = DataSourceContent(**ls)
            db.session.add(content)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(code=500, msg='Error'), 500
    finally:
        if os.path.exists(path_file := settings.UPLOAD_FOLDER / filename):
            os.remove(str(path_file))
    return jsonify(status=200, msg='Success', title_id=query_title.id), 200
